#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2018/11/6 18:04
@desc
"""

from pyhive import hive
from TCLIService.ttypes import TOperationState


class HiveOpr():

    def __init__(self, host, port):
        self.hiveConn = hive.connect(host=host, port=port)
        self.cursor = self.hiveConn.cursor()

    def __del__(self):
        self.cursor.close()
        self.hiveConn.close()

    def fetchrow(self, sql, anync_bool):
        self.cursor.execute(sql, anync=anync_bool)
        # 得到执行语句的状态
        status = self.cursor.poll().operationState
        print("status:", status)

        # 如果执行出错，循环执行，直到执行正确，可不要
        while status in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):
            logs = self.cursor.fetch_logs()
            for message in logs:
                print(message)
            # If needed, an asynchronous query can be cancelled at any time with:
            # cursor.cancel()
            status = self.cursor.poll().operationState
        return self.cursor.fetchall()

    def havetable(self, schema_name, table_name):
        try:
            self.execsql('desc %s.%s' % (schema_name, table_name), True)
            havetable = True
        except Exception as e:
            havetable = False
        return havetable

    def execsql(self, sql, anync_bool):
        self.cursor.execute(sql, anync=anync_bool)
        # 得到执行语句的状态
        status = self.cursor.poll().operationState
        return status

    def gen_cycle_del_sql(self, databasename, tablename, cyclevalue):
        return "ALTER TABLE %s.%s DROP IF EXISTS PARTITION (DEAL_DATE_P='%s');" % (databasename, tablename, cyclevalue)

    def gen_cycle_add_sql(self, databasename, tablename, cyclevalue):
        return "ALTER TABLE %s.%s ADD IF NOT EXISTS PARTITION (DEAL_DATE_P='%s');" % (databasename, tablename, cyclevalue)

if __name__ == '__main__':
    hiveopr = HiveOpr('192.168.100.151', 10000)
    selectSet = hiveopr.execsql('select * from ptemp3.teradata', True)
    for i in selectSet:
        print(i)

#     sql = """CREATE TABLE ptemp3.tb_teradata_parquet
#      (
#      DEAL_DATE STRING COMMENT '',
#       taskid VARCHAR(64),
#       url VARCHAR(1024),
#       result BINARY,
#       updatetime FLOAT
#       )
# COMMENT 'teradata'
# PARTITIONED BY (DEAL_DATE_P DATE COMMENT '')
# ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
# STORED AS PARQUET TBLPROPERTIES("PARQUET.COMPRESSION"="SNAPPY")"""
#
#
#     createstat = hiveopr.ddlsql(sql, True)
#     print(createstat)
#
#
#     dropret = hiveopr.ddlsql("drop table ptemp3.tb_teradata_parquet", True)
#     print(dropret)
